package jgo.plugins.auth;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import jgo.Context;
import jgo.JGo;
import jgo.User;
import jgo.plugins.server.HttpContext;

public class SimpleAuthorizationPlugin extends AuthorizationPlugin {
    private Map<String, Set<String>> userPermissions = new HashMap<>();

    @Override
    public void init(JGo gin) {
        // 初始化逻辑，可以从配置文件或数据库加载权限信息
    }

    @Override
    public String name() {
        return "SimpleAuthorization";
    }

    @Override
    public boolean isAuthorized(Context ctx, String resource, String action) {
        User user = ((HttpContext) ctx).user;
        if (user == null) {
            return false; // 如果用户未登录，则没有权限
        }
        String userId = user.getId();
        Set<String> permissions = userPermissions.getOrDefault(userId, new HashSet<>());
        return permissions.contains(resource + ":" + action);
    }

    public void addPermission(String userId, String resource, String action) {
        userPermissions.computeIfAbsent(userId, k -> new HashSet<>()).add(resource + ":" + action);
    }
}